package com.umer.pinban.customer;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.bean.UserInfo;
import com.common.okhttp.OkEntityListRequest;
import com.common.okhttp.OkSimpleRequest;
import com.common.ui.loadsir.callback.EmptyCallback;
import com.common.ui.loadsir.callback.ErrorCallback;
import com.common.ui.loadsir.callback.NoNetCallback;
import com.common.ui.recycleview.listener.DataStateListener;
import com.common.ui.recycleview.listener.OptListener;
import com.common.utils.Constants;
import com.common.utils.EventConstants;
import com.common.utils.screen.ScreenUtil;
import com.umer.pinban.AppHolder;
import com.umer.pinban.R;
import com.umer.pinban.adapter.customer.TipsRecordAdapter;
import com.umer.pinban.base.BasicFragment;
import com.umer.pinban.bean.customer.TipListBean;
import com.umer.pinban.bean.staff.StaffBean;
import com.umer.pinban.staff.SelectStaffActivity;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;

public class TipsFragment extends BasicFragment implements OptListener, DataStateListener,
        DatePickerDialog.OnDateSetListener {

    private static int customerId;
    private static String customerName = "";
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    private TipsRecordAdapter tipsRecordAdapter;
    private List<TipListBean> remindListBeans = new ArrayList<>();
    private String dayTime = "";
    private int remindId;
    private UserInfo userInfo;

    public static TipsFragment newInstance(int argument1, String argument2) {
        customerId = argument1;
        customerName = argument2;
        return new TipsFragment();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return llContent;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_customer_tip;
    }

    @Override
    public void init() {
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        userInfo = AppHolder.getInstance().getUserInfo();
        initView();
    }

    @Override
    public void loadData() {
        customerTipsRecordList();
    }

    @Override
    public void onOptClick(View view, Object object) {
        int position = (int) object;
        remindId = tipsRecordAdapter.getDataSource().get(position).getRemindId();
        switch (view.getId()) {
            case R.id.iv_edit:
                personnelId = tipsRecordAdapter.getDataSource().get(position).getPersonnelId();
                personnelName = tipsRecordAdapter.getDataSource().get(position).getPersonnelName();
                remindDate = tipsRecordAdapter
                        .getDataSource().get(position).getRemindDate().replace("00:00:00", "").trim();
                remark = tipsRecordAdapter.getDataSource()
                        .get(position).getRemark();
                showDialog();
                break;
            case R.id.iv_delete:
                new MaterialDialog.Builder(getActivity())
                        .title("确认删除")
                        .content("是否删除此提醒")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                deleteTip();
                            }
                        })
                        .positiveText("确定")
                        .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary))
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            }
                        })
                        .negativeText("取消")
                        .negativeColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary))
                        .show();
                break;
            default:
                break;
        }
    }

    @Override
    public void handlerMeg(MsgBean msgBean) {
        super.handlerMeg(msgBean);
        int flag = msgBean.getFlag();
        if (flag == EventConstants.select_staff) {
            StaffBean staffBean = (StaffBean) msgBean.getObject();
            if (staffBean != null) {
                personnelId = staffBean.getPersonnelId();
                personnelName = staffBean.getName();
            } else {
                personnelId = -1;
                personnelName = "";
            }
            tv_personnel.setText(personnelName);
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        switch (what) {
            case R.id.remindList:
                swipeRefreshLayout.setRefreshing(false);
                remindListBeans = (List<TipListBean>) t.getT();
                tipsRecordAdapter.setDataSource2(remindListBeans, t);
                break;
            case R.id.deleteCustomerRemind:
            case R.id.editCustomerRemind:
                hideProgress();
                loadData();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {
        switch (what) {
            case R.id.remindList:
                swipeRefreshLayout.setRefreshing(false);
                remindListBeans = (List<TipListBean>) t.getT();
                tipsRecordAdapter.setDataSource2(remindListBeans, t);
                break;
            case R.id.editCustomerRemind:
                hideProgress();
                showToast(t.getDesc());
            default:
                break;
        }
    }

    @Override
    public void onDataState(int flag) {
        //1:没有网络 2:没有数据 3:获取数据失败 4:显示内容
        switch (flag) {
            case 1:
                if (loadService != null) {
                    loadService.showCallback(NoNetCallback.class);
                }
                break;
            case 2:
                if (loadService != null) {
                    loadService.showCallback(EmptyCallback.class);
                }
                break;
            case 3:
                if (loadService != null) {
                    loadService.showCallback(ErrorCallback.class);
                }
                break;
            case 4:
                if (loadService != null) {
                    loadService.showSuccess();
                }
                break;
            default:
                break;
        }
    }

    private void initView() {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
                R.color.colorPrimary,R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
        tipsRecordAdapter = new TipsRecordAdapter(getActivity(), remindListBeans,
                R.layout.fragment_tips_item, this, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(tipsRecordAdapter);
       /* //单击
        ItemClickSupport.addTo(pullLoadMoreRecyclerView.getRecyclerView())
                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                    }
                });
        //长按
        ItemClickSupport.addTo(pullLoadMoreRecyclerView.getRecyclerView()).setOnItemLongClickListener(new ItemClickSupport.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
                return false;
            }
        });*/
    }

    private void customerTipsRecordList() {
        OkEntityListRequest<TipListBean> request = new OkEntityListRequest<>(R.id.remindList,
                Constants.remindList, TipListBean.class);
        request.addParams("dayTime", dayTime);
        request.addParams("customerId", customerId);
        request.setHeader(true);
        requestOkhttpEntityList(request);
    }

    private void deleteTip() {
        showProgress("正在请求...");
        OkSimpleRequest okSimpleRequest = new OkSimpleRequest(R.id.deleteCustomerRemind,
                Constants.deleteCustomerRemind);
        okSimpleRequest.addParams("remindId", remindId);
        okSimpleRequest.setHeader(true);
        requestOkhttpSimple(okSimpleRequest);
    }

    private void editTips() {
        showProgress("正在提交...");
        OkSimpleRequest okSimpleRequest = new OkSimpleRequest(R.id.editCustomerRemind,
                Constants.editCustomerRemind);
        okSimpleRequest.addParams("remindId", remindId);
        okSimpleRequest.addParams("customerId", customerId);
        okSimpleRequest.addParams("personnelId", personnelId);
        okSimpleRequest.addParams("shopId", userInfo.getShopId());
        okSimpleRequest.addParams("remark", remark);
        okSimpleRequest.addParams("remindDate", remindDate + " 00:00:00");
        okSimpleRequest.setHeader(true);
        requestOkhttpSimple(okSimpleRequest);
    }

    private Dialog dialogTip;
    private TextView tv_personnel, tv_time, tv_customer_name, tv_xiugai;
    private EditText et_tips_remark;
    private LinearLayout linear_personnel, linear_time;
    private ImageView imageViewTip;
    private int personnelId = -1;
    private String personnelName = "";
    private String remindDate = "";
    private SimpleDateFormat simpleDateFormat;
    private String remark = "";

    private void showDialog() {
        if (dialogTip == null) {
            dialogTip = new Dialog(getActivity(), R.style.ActionSheetDialogStyle);
            //填充对话框的布局
            View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_tip_edit, null);
            imageViewTip = (ImageView) inflate.findViewById(R.id.image2);
            tv_xiugai = (TextView) inflate.findViewById(R.id.tv_xiugai);
            tv_personnel = (TextView) inflate.findViewById(R.id.tv_personnel);
            tv_customer_name = (TextView) inflate.findViewById(R.id.tv_customer_name);
            tv_time = (TextView) inflate.findViewById(R.id.tv_time);
            linear_personnel = (LinearLayout) inflate.findViewById(R.id.linear_personnel);
            linear_time = (LinearLayout) inflate.findViewById(R.id.linear_time);
            et_tips_remark = (EditText) inflate.findViewById(R.id.et_tips_remark);
            tv_time.setText(remindDate);
            tv_customer_name.setText(customerName);
            et_tips_remark.setText(remark);
            tv_personnel.setText(personnelName);

            linear_personnel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), SelectStaffActivity.class);
                    intent.putExtra("staffId", personnelId);
                    startActivity(intent);
                }
            });
            linear_time.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setDate();
                }
            });
            imageViewTip.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialogTip.isShowing()) {
                        dialogTip.dismiss();
                    }
                }
            });
            tv_xiugai.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(personnelName)) {
                        showToast("请选择优美师");
                    } else if (TextUtils.isEmpty(remark)) {
                        showToast("请输入提醒");
                    } else {
                        if (dialogTip.isShowing()) {
                            dialogTip.dismiss();
                        }
                        editTips();
                    }
                }
            });
            et_tips_remark.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        remark = s.toString();
                    }
                }
            });
            //将布局设置给Dialog
            dialogTip.setContentView(inflate);
            Window dialogWindow = dialogTip.getWindow();
            WindowManager.LayoutParams windowparams = dialogWindow.getAttributes();
            //设置Dialog从窗体底部弹出
            dialogWindow.setGravity(Gravity.TOP);
            Rect rect = new Rect();
            View view1 = dialogWindow.getDecorView();
            view1.getWindowVisibleDisplayFrame(rect);
            windowparams.width = ScreenUtil.getInstance().getScreenWidth();
            dialogWindow.setAttributes(
                    (WindowManager.LayoutParams) windowparams);
            //获得窗体的属性
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            lp.y = 10;//设置Dialog距离底部的距离
//            //将属性设置给窗体
//            dialogWindow.setAttributes(lp);
            dialogTip.show();
        } else {
            if (!dialogTip.isShowing()) {
                et_tips_remark.setText(remark);
                tv_time.setText(remindDate);
                tv_customer_name.setText(customerName);
                tv_personnel.setText(personnelName);
                dialogTip.show();
            }
        }
    }

    private void setDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                TipsFragment.this,
                now.get(Calendar.YEAR), // Initial year selection
                now.get(Calendar.MONTH), // Initial month selection
                now.get(Calendar.DAY_OF_MONTH) // Inital day selection
        );
        dpd.show(getFragmentManager(), "Datepickerdialog");
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        remindDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
        tv_time.setText(remindDate);
    }
}
